<?php
/**
 * Created by PhpStorm.
 * User: xding
 * Date: 15/10/19
 * Time: 上午10:22
 */

class Tags_model extends CI_Model {


    private $tb_name    = 'tags';

    private $tags_array = NULL;

    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->initialize();
    }


    private function initialize() {
        $this->tags_array = $this->dg_get_tag();
    }


    private function dg_get_tag( $parent = 0, $deep = 0 ) {
        static $_tag_array = array();

        $this->db->where('parent',$parent);
        $query = $this->db->get($this->tb_name);

        if (!$query->num_rows())
        {
            return NULL;
        }
        else
        {
            0 === $parent && $deep ++;
        }


        foreach ( $query->result()  as $row )
        {
            array_push($_tag_array,$row);
            $this->dg_get_tag($row->ID,$deep);
        }

        return $_tag_array;
    }



    public function get_tags() {
        return $this->tags_array;
    }

    /**
     * 更具ID数组，获取Tag
     *
     * @param $ids_array
     * @return array|null
     */
    public function get_tag_arr_by_ids($ids_array) {
        if ( !count($ids_array) )
        {
            return NULL;
        }

        $search_result = array();
        foreach ( $this->tags_array as $tag )
        {
            if ( in_array($tag->ID,$ids_array) )
                array_push($search_result,$tag);
        }

        if ( !count($search_result) )
        {
            return NULL;
        }

        return $search_result;
    }

}